package main

import (
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"go-yuque/entity"
	"go-yuque/logger"
	"go-yuque/yqRouter"
	"io"
	"net/http"
	"time"
)

/**
  go get -u github.com/PuerkitoBio/goquery
  go get -u gopkg.in/yaml.v3
  go get -u github.com/gin-gonic/gin
  go get -u github.com/gin-contrib/sessions
  go get -u github.com/robfig/cron/v3
  go get -u github.com/gin-contrib/sessions/memstore
  go get -u github.com/gin-contrib/sessions/redis
*/

func init() {

	gin.SetMode(gin.DebugMode)

	f, err := logger.InitLog(&logger.LogConfigStruct{
		LogDir:        "./log",
		LogNamePrefix: "yuque",
	})

	if err == nil && f != nil {
		// 异常日志重定向到文件和控制台
		gin.DefaultWriter = io.MultiWriter(f, gin.DefaultWriter)
		gin.DefaultErrorWriter = io.MultiWriter(f, gin.DefaultErrorWriter)
	}

}

func main() {

	defer func() {
		if err := recover(); err != nil {
			logger.Errorf("panic:%v", err)
		}
	}()

	router := gin.Default()

	// 不显示设置会导致使用IP访问时无法存入Cookie
	yqRouter.SessionStore.Options(sessions.Options{
		Domain:   "", // 留空或设为 IP（如 "192.168.1.100"）
		Path:     "/",
		MaxAge:   3600 * 24 * 7,
		Secure:   false, // 本地测试用 HTTP 时设为 false
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode, // 本地测试可暂用 Lax
	})
	// 设置session中间件，参数mysession，指的是session的名字，也是cookie的名字
	// store是前面创建的存储引擎
	router.Use(sessions.Sessions(yqRouter.SessionIdCookieName, yqRouter.SessionStore))

	router.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "Hello World",
		})
	})

	router.Delims("{[{", "}]}")

	router.Static("/static/", "static/")

	// matches, _ := filepath.Glob("static/html/**/*")
	// logger.Infof("matches:%v", matches)

	router.LoadHTMLGlob("tmpl/**/*")
	yqRouter.InitPageRouter(router)
	yqRouter.InitApiRouter(router)

	logger.Infof("启动:%s\n", time.Now().Format("2006-01-02 15:04:05"))
	logger.Infof("open: http://127.0.0.1:%d", entity.GetServerPort())
	logger.Infof("or open: http://127.0.0.1:%d/page/index", entity.GetServerPort())
	err := router.Run(fmt.Sprintf(":%d", entity.GetServerPort()))
	if err != nil {
		logger.Errorf("启动报错:%v\n", err)
	}
}
